using Microsoft.AspNetCore.Mvc;
using JS.Models;

namespace JS.Controllers;

public class StudentController : Controller
{
     public IActionResult Index()
    {
        return View(Stus.StudentList);
    }
     public IActionResult Find(string keyword)
    {
        dynamic data;
        if (string.IsNullOrEmpty(keyword))
        {
            data = Stus.StudentList;
        }
        else
        {
            data = Stus.StudentList.Where(item =>
                    {
                        return item.StudentName.Contains(keyword)
                        || item.Gender.Contains(keyword);
                        || item.Birth.Contains(keyword);
                    });
        }
         var res = new
        {
            Code = 3000,
            data,
            msg = "查找成功"
        };
        return Json(res);
    }
    [HttpDelete]
    public IActionResult Del(int id)
    {
        
        dynamic obj;
        var tmp = Stus.StudentList.Find(item =>
        {
            return item.Id == id;
        });

        
        if (tmp != null)
        {
            
            Stus.StudentList.Remove(tmp);
          
            obj = new
            {
                Code = 3000,
                Data = new { Id = id, RemainStudent = Stus.StudentList },
                msg = "删除成功"
            };
        }
        else
        {
          
            obj = new
            {
                Code = 3000,
                Data = new { Id = id, RemainStudent = Stus.StudentList },
                msg = "没有找到对应id的学生,删除失败"
            };
        }

     
        return Json(obj);
    }
      public IActionResult Edit(int id)
    {
        var stu=Stus.StudentList.FirstOrDefault(item =>
        {
            return item.Id == id;
        });
        return View(stu);
    }
     public IActionResult Save(int id,Students stu)
    {
         dynamic res;
         var stu=Stus.StudentList.FirstOrDefault(item =>
        {
            return item.Id == id;
        });
        if (student != null)
        {
            student.StudentName = stu.StudentName;
            student.Birth = stu.Birth;
            student.Gender = stu.Gender;
            res = new
            {
                Code = 3000,
                Msg = "修改成功"
            };
        }
        
         else
        {
            Stus.StudentList.Add(stu);
            res = new
            {
                Code = 3000,
                Msg = "数据中未有此数据已为您添加"
            };
 
       }
       return Json(res);
    }
    }

